<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片面板-->
    <el-card class="box-card">
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条-->
      <el-steps :space="400" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addForm"
        :rules="addFormRule"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- tab 选项卡 -->
        <el-tabs tab-position="left" v-model="activeIndex" style="margin-top:15px;">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="addForm.price" type="number"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="1">
            <el-upload
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              :http-request="uploadHttp"
              :before-upload="beforeAvatarUpload"
              list-type="picture"
            >
              <el-button size="small" type="primary">上传商品图片</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="2">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品 -->
            <el-button type="primary" class="btnAdd" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import ossClient from '../../aliyun.oss.client'

export default {
  data() {
    return {
      // 步骤条默认激活 与左侧Tab联动
      activeIndex: '0',
      addForm: {
        name: '',
        price: 0,
        // 图片的数组
        imgs: {},
        // 商品详情描述
        desc: ''
      },
      // 订单
      addFormRule: {
        // 验证名称
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 8, max: 30, message: '长度在 8 到 30 个字符', trigger: 'blur' }
        ],
        // 验证价格
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }]
      },
      fileList: []
    }
  },
  methods: {
    /**
     * 阿里云OSS上传
     */
    uploadHttp({ file }) {
      console.log(file)
      const $self = this
      const conf = {
        region: 'oss-cn-hangzhou',
        accessKeyId: 'LTAI4G5Ws1ZybRpuocvFq3EG',
        accessKeySecret: 'ZMJ26p83D7vAp9POOy9DNUej83XDdt',
        bucket: 'airpass-training'
      }
      const imgName = 'ALIOSS_IMG_'
      // 定义唯一的文件名
      const fileName = `${imgName}/${Date.parse(new Date())}.${
        file.name.split('.')[1]
      }`
      console.log(fileName)
      ossClient(conf)
        .put(fileName, file, {
          ContentType: 'image/jpeg'
        })
        .then(({ res, url, name }) => {
          if (res && res.status === 200) {
            console.log('阿里云OSS上传图片成功回调', res, url, name)
            $self.addForm.imgs[file.uid] = name
          }
        })
        .catch(err => {
          console.log('阿里云OSS上传图片失败回调', err)
        })
    },
    /**
     * 图片限制
     */
    beforeAvatarUpload(file) {
      const isJPEG = file.name.split('.')[1] === 'jpeg'
      const isJPG = file.name.split('.')[1] === 'jpg'
      const isPNG = file.name.split('.')[1] === 'png'
      const isLt500K = file.size / 1024 / 500 < 2
      if (!isJPG && !isJPEG && !isPNG) {
        this.$message.error('上传图片只能是 JPEG/JPG/PNG 格式!')
      }
      if (!isLt500K) {
        this.$message.error('单张图片大小不能超过 500KB!')
      }
      return (isJPEG || isJPG || isPNG) && isLt500K
    },
    handleSuccess(response, file, fileList) {},
    /**
     * 移除图片
     */
    handleRemove(file, fileList) {
      delete this.addForm.imgs[file.uid]
    },
    async addGoods() {
      // 添加商品
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          this.$message.error('请完善表单内容！')
          return false
        }
        const imgs = Object.values(this.addForm.imgs)
        if (imgs.length < 1) {
          this.$message.error('请至少上传一个商品图片！')
          return false
        }
        const params = {
          name: this.addForm.name,
          price: this.addForm.price,
          imgs: imgs,
          shopId: 'B-000000'
        }
        // 请求数据
        const { data: ret } = await this.$http.post('/item/add', params, {
          transformRequest: [
            function(data) {
              let ret = ''
              for (const it in data) {
                ret +=
                  encodeURIComponent(it) +
                  '=' +
                  encodeURIComponent(data[it]) +
                  '&'
              }
              return ret
            }
          ],
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          withCredentials: true
        })
        if (ret.rc !== 'S') return this.$message.error('添加商品失败，异常编码！' + ret.rc)
        this.$message.success('添加成功')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.btnAdd {
  margin-top: 15px;
}
</style>
